import { zhooks } from 'ym-design'

import { useState } from 'react';
const { useRequest } = zhooks
function getUsername(type: 'success' | 'error') {
  console.log('polling getUsername');
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (type === 'success') {
        resolve(Math.random() + '@name');
      } else {
        reject(new Error('Failed to get username'));
      }
    }, 1000);
  });
}

function HookUseRequestPlling() {
  const [pollingInterval, setPollingInterval] = useState(3000);

  const { data, loading, run, cancel, refresh, error, params } = useRequest(getUsername, {
    pollingInterval,
    pollingWhenHidden: false,
    pollingErrorRetryCount: 3,
    onBefore: () => {
      console.log('--polling--onBefore--');
    },
    onSuccess: (data:any, params:any) => {
      console.log('--polling--onSuccess--data--params--', data, params);
    },
    onFinally: (params:any, data:any, error:any) => {
      console.log('--polling--onFinally--params--data--error--:', params, data, error);
    },
    onError: (error:any) => {
      console.log('--polling--onError--', error);
    },
  });

  return (
    <div>
      <h3>轮询：轮询.pollingErrorRetryCount和错误重试功能重复</h3>
      <div>
        <p>
          params:
          {params?.map((p:any, pIndex:any) => (
            <span key={pIndex}>{p}</span>
          ))}
        </p>
        <p>data:{data as any}</p>
      </div>

      {error && <div style={{ color: 'red' }}>{error.message}</div>}
      <button
        disabled={loading}
        onClick={() => {
          run('success');
        }}
      >
        开始轮询
      </button>

      <button onClick={cancel}>取消轮询</button>

      <button
        onClick={() => {
          setPollingInterval(0);
          refresh();
        }}
      >
        仅仅refresh接口一次，不要轮询
      </button>
      <button onClick={() => run('error')}>请求错误后再重试3次</button>
    </div>
  );
}

export default HookUseRequestPlling;